package com.ztools.pc.provider;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.ztools.api.service.pc.ApiService;
import com.ztools.common.util.common.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.data.redis.core.StringRedisTemplate;

import javax.annotation.Resource;
import java.util.Date;
import java.util.concurrent.TimeUnit;

import static com.ztools.common.util.common.UrlUtil.MX_NZP_AUTHENTICATION;
import static com.ztools.common.util.common.UrlUtil.MX_NZP_RECOMMEND;
import static com.ztools.common.util.pc.RedisUtil.CACHE_MX_NZP_JOKES;

/**
 * @Author: seeTools
 * @Date: 2023/7/12  16:44
 * @Version 1.0
 */
@Slf4j
@Service(version = "1.0", timeout = 3000)
public class ApiServiceImpl implements ApiService {


    @Resource
    private StringRedisTemplate stringRedisTemplate;


    @Override
    public Result findJokes() {
        String url = MX_NZP_RECOMMEND + "?" + MX_NZP_AUTHENTICATION;
        String redisData = stringRedisTemplate.opsForValue().get(CACHE_MX_NZP_JOKES);
        if (StrUtil.isNotEmpty(redisData)) {
            return Result.success().data(JSONUtil.parseArray(redisData));
        }
        String result = HttpUtil.get(url);
        if (StrUtil.isNotEmpty(result) && JSONUtil.isJson(result)) {
            JSONObject jsonObject = JSONUtil.parseObj(result);
            log.info("调用findJokes结果为:" + JSONUtil.toJsonStr(jsonObject));
            String code = jsonObject.getStr("code");
            if ("1".equals(code)) {
                String data = jsonObject.getStr("data");
                if (StrUtil.isNotEmpty(data) && JSONUtil.isJson(data)) {
                    // 获取到时间
                    Date date = new Date();
                    DateTime dateTime = DateUtil.endOfDay(date);
                    long second = DateUtil.between(date, dateTime, DateUnit.SECOND);
                    JSONArray jsonArray = JSONUtil.parseArray(data);
                    stringRedisTemplate.opsForValue().set(CACHE_MX_NZP_JOKES, JSONUtil.toJsonStr(jsonArray), second, TimeUnit.SECONDS);
                    return Result.success().data(jsonArray);
                }
            }
        }
        return Result.error();
    }
}
